<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use think\Config;
use think\Controller;
use think\Session;
use think\Validate;

class Login extends Controller
{
    private $mod;
    private $rule;
    private $msg;

    public function _initialize()
    {
        $this->mod = new Admin();
		$this->rule = [
				'name' => 'require|max:25',
				'password' => 'require|alphaDash|length:6,25'
		];
		$this->msg = [
				'name.require' => '姓名必填',
				'password.require' => '密码必填',
				'password.alphaDash' => '密码必须为字母和数字，下划线_及破折号-',
				'password.length' => '密码长度必须为6~25位'
		];
    }

    /**
     * 登录
     * @return array|\think\response\View
     */
    public function index()
    {
        if ($this->request->isPost() && $this->request->isAjax()) {
            $data = $this->request->param();

            if(!captcha_check($data['code'])){
                return ['status'=>'0','msg'=>'验证码错误，请重新输入'];
            };

            $validate = new Validate($this->rule, $this->msg);
            if ($validate->check($data) !== true) {
                return ['status'=>'0','msg'=>$validate->getError()];
            }

            $where = ['name'=>$data['name'], 'is_work'=>1];
            $order ['id'] = 'desc';
            $row = $this->mod->field('id,name,password')->where($where)->order($order)->find();
            $password = md5(md5($data['password']));
            if ($row['password'] != $password) {
                return ['status'=>'0','msg'=>'密码错误，请重新输入'];
            }

            Session::set(Config::get('session_prefix').'id',$row['id']);
            Session::set(Config::get('session_prefix').'name',$row['name']);
            Session::set(Config::get('session_prefix').'pwd',md5(Config::get('session_prefix').$password));
            unset($row);

            return ['status'=>'1', 'msg'=>'成功登录'];
        } else {
            return view();
        }
    }

    /**
     * 检查是否登录
     * @return bool
     */
    public function checkLogin(){
        $id = Session::get(Config::get('session_prefix').'id');
//        $name = Session::get(Config::get('session_prefix').'name');
        $pwd = Session::get(Config::get('session_prefix').'pwd');

        $where = ['id'=>$id, 'is_work'=>1];
        $order ['id'] = 'desc';
        $password = $this->mod->where($where)->value('password');
        $password = md5(Config::get('session_prefix').$password);
        if ($pwd == $password) {
            return true;
        }
        return false;
    }

    /**
     * 注销登录
     */
    public function loginOut() {
        Session::delete(Config::get('session_prefix').'id');
        Session::delete(Config::get('session_prefix').'name');
        Session::delete(Config::get('session_prefix').'pwd');
        $this->redirect('Login/index');
    }

}